#include "thread_file_logger.h"

thread_file_logger *thread_file_logger::m_inst=NULL;
recursive_mutex     thread_file_logger::m_lock;

thread_file_logger::thread_file_logger()
{
    m_queue.set_call_backs(this, &thread_file_logger::handle_msg);
    m_queue.thread_begin();
}

thread_file_logger::~thread_file_logger()
{
    m_queue.thread_syncstop();
}

void thread_file_logger::handle_msg(const char *pmsgin, int nsize)
{
    log_msg *pmsg = (log_msg *)pmsgin;
    std::cout<<(const char *)pmsg+sizeof(log_msg);
}



thread_file_logger *thread_file_logger::get_inst()
{
    recursive_mutex::scoped_lock lock(m_lock);
    if (!m_inst)
    {
        m_inst = new thread_file_logger();
    }
    return m_inst;
}

std::string thread_file_logger::get_time_str()
{
#ifdef _WIN32
    SYSTEMTIME st;
    GetLocalTime ( &st );
    std::ostringstream oss;
    oss<<st.wYear<<st.wMonth<<st.wDay<<"_"<<st.wHour<<st.wMinute<<st.wSecond;
    return oss.str();
#else
    char szBuf[256] =
    { 0 };
    time_t timer = ::time(NULL);
    strftime(szBuf, sizeof(szBuf), "%Y-%m-%d_%H%M%S", localtime(&timer));
    return szBuf;
#endif
}

void thread_file_logger::post_log_msg( std::ostringstream &oss )
{
    log_msg msg;
    std::string str = oss.str();
    msg.size = str.length()+1;        
    m_queue.post_msg(&msg, sizeof(log_msg), str.c_str(), msg.size);
}
